package cn.getech.data.development.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import java.io.*;
import java.util.List;

@Slf4j
public class WindowsFTP {

    public FTPClient ftpClient = new FTPClient();

    /**
     * 连接到FTP服务器
     *
     * @param hostname 主机名
     * @param port 端口
     * @param username 用户名
     * @param password 密码
     * @return 是否连接成功
     * @throws IOException
     */
    public boolean connect(String hostname, int port, String username, String password)
            throws Exception
    {

        try
        {
            ftpClient.connect(hostname, port);
        }
        catch (Exception e)
        {
            throw new Exception("登陆异常，请检查主机端口");
        }
        ftpClient.setControlEncoding("GBK");
        if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode()))
        {
            if (ftpClient.login(username, password))
            {
                return true;
            }
            else
                throw new Exception("登陆异常，请检查密码账号");
        }
        else
            throw new Exception("登陆异常");

    }

    public void initFileList(List<String> tmpLists, String filedir)
            throws IOException
    {
        ftpClient.enterLocalPassiveMode();
        FTPFile[] files = ftpClient.listFiles(filedir);
        if (files != null)
        {
            for (int i = 0; i < files.length; i++)
            {
                tmpLists.add(files[i].getName());
            }
        }
    }

    /**
     * 断开与远程服务器的连接
     *
     * @throws IOException
     */
    public void disconnect()
    {
        if (ftpClient != null && ftpClient.isConnected())
        {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}